package cn.com.south.serive;

import cn.com.south.entity.User;
import cn.com.south.mapper.UserMapper;
import cn.com.south.utils.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 进行用户登录自定义过滤
 * @author south
 * date 2021/12/30 21:36
 * @version v1.0.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username);
        logger.info("loadUserByUsername username:[{}]",username);
        //如果用户不存在
        if (user == null){
            throw new UsernameNotFoundException(username + "用户不存在");
        }
        return new org.springframework.security.core.userdetails.User(username, MD5Utils.encode(user.getPassword()),
                true,true,true,true,
                AuthorityUtils.createAuthorityList(user.getRole()));
    }
}
